﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Web;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace BaiduTransLib
{

    public class TransObj
    {
        public string from { get; set; }
        public string to { get; set; }
        public List<TransResult> trans_result { get; set; }
    }

    public class TransResult
    {
        public string src { get; set; }
        public string dst { get; set; }
    }


    public class TranslateQuery
    {
        int Salt;
        string m_appKey;
        string m_sign;

        public TranslateQuery(string appid, string appKey,string q,BaiduTransLang from=BaiduTransLang.zh,BaiduTransLang sto=BaiduTransLang.en)
        {
            appID = appid;
            Query = q;
            langFrom = from.ToString();
            langTo = sto.ToString();
            Salt = new Random().Next(10000, 99999);
            m_appKey = appKey;
            m_sign = buildSign();
        }

        public string GetQueryString()
        {
            return String.Format("q={0}&appid={1}&salt={2}&from={3}&to={4}&sign={5}",
                                  System.Web.HttpUtility.UrlEncode(Query),
                                  appID,
                                  Salt,
                                  langFrom,
                                  langTo,
                                  m_sign
                );
        }

        private string buildSign()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(appID);
            sb.Append(Query);
            sb.Append(Salt);
            sb.Append(m_appKey);

            string ret = String.Empty;

            using (MD5 md5hash = MD5.Create())
            {
                ret = GetMd5Hash(md5hash, sb.ToString());
            }

            return ret;
        }

        string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
        public string appID { get; set; }
        public string Query { get; set; }
        public string langFrom { get; set; }
        public string langTo { get; set; }
    }

    public class BaiduTranslate
    {
        string m_appID;
        string m_appKey;
        string url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        Dictionary<string, string> Lang_list;
        public BaiduTranslate(string appid,string appkey)
        {
            m_appID = appid;
            m_appKey = appkey;

            InitLangList();
        }

        private void InitLangList()
        {
            Lang_list = new Dictionary<string, string>();
            Lang_list.Add("auto", @"自动检测");
            Lang_list.Add("zh", @"中文");
            Lang_list.Add("en", @"英语");
            Lang_list.Add("yue", @"粤语");
            Lang_list.Add("wyw", @"文言文");
            Lang_list.Add("jp", @"日语");
            Lang_list.Add("kor", @"韩语");
            Lang_list.Add("fra", @"法语");
            Lang_list.Add("spa", @"西班牙语");
            Lang_list.Add("th", @"泰语");
            Lang_list.Add("ara", @"阿拉伯语");
            Lang_list.Add("ru", @"俄语");
            Lang_list.Add("pt", @"葡萄牙语");
            Lang_list.Add("de", @"德语");
            Lang_list.Add("it", @"意大利语");
            Lang_list.Add("el", @"希腊语");
            Lang_list.Add("nl", @"荷兰语");
            Lang_list.Add("pl", @"波兰语");
            Lang_list.Add("bul", @"保加利亚语");
            Lang_list.Add("est", @"爱沙尼亚语");
            Lang_list.Add("dan", @"丹麦语");
            Lang_list.Add("fin", @"芬兰语");
            Lang_list.Add("cs", @"捷克语");
            Lang_list.Add("rom", @"罗马尼亚语");
            Lang_list.Add("slo", @"斯洛文尼亚语");
            Lang_list.Add("swe", @"瑞典语");
            Lang_list.Add("hu", @"匈牙利语");
            Lang_list.Add("cht", @"繁体中文");
        }

        public String Translate(string q,BaiduTransLang langfrom=BaiduTransLang.zh,BaiduTransLang langto=BaiduTransLang.en)
        {
            TranslateQuery query = new TranslateQuery(m_appID, m_appKey, q, langfrom, langto);

            string webUrl = query.GetQueryString();


            string realUrl = url + @"?" + webUrl;

            HttpWebRequest m_request = (HttpWebRequest)WebRequest.Create(realUrl);

            HttpWebResponse response = (HttpWebResponse)m_request.GetResponse();

            //Console.WriteLine("Content length is {0}", response.ContentLength);
            //Console.WriteLine("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader(receiveStream);

            //Console.WriteLine("Response stream received.");                        
            string s=readStream.ReadToEnd();

            JsonTextReader jsonReader = new JsonTextReader(new StringReader(s));
            JsonSerializer serializer = new JsonSerializer();
            var r = serializer.Deserialize<TransObj>(jsonReader);
            return r.trans_result[0].dst;
        }       
    }

    public enum BaiduTransLang
    {
        auto,   //自动检测
        zh,     //中文
        en,     //英语
        yue,    //粤语
        wyw,    //文言文
        jp,     //日语
        kor,    //韩语
        fra,    //法语
        spa,    //西班牙语
        th,     //泰语
        ara,    //阿拉伯语
        ru,     //俄语
        pt,     //葡萄牙语
        de,     //德语
        it,     //意大利语
        el,     //希腊语
        nl,     //荷兰语
        pl,     //波兰语
        bul,    //保加利亚语
        est,    //爱沙尼亚语
        dan,    //丹麦语
        fin,    //芬兰语
        cs,     //捷克语
        rom,    //罗马尼亚语
        slo,    //斯洛文尼亚语
        swe,    //瑞典语
        hu,     //匈牙利语
        cht,    //繁体中文
    }
}
